import webbrowser
def start_browser():
    url = "http://localhost:17520"
    webbrowser.open_new_tab(url)

import os  # 导入 os 模块

import sys  # 导入 sys 模块

from routes.print import print_app


root_path = os.getcwd()  # 获取当前工作目录
sys.path.append(root_path)  # 将当前工作目录添加到 sys.path 中

from fastapi import FastAPI
from fastapi.staticfiles import StaticFiles
from fastapi.responses import FileResponse
from fastapi.middleware.cors import CORSMiddleware
import uvicorn



app = FastAPI()
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

app.include_router(print_app,prefix='/print', tags=["打印"])



current_dir = os.path.dirname(os.path.abspath(__file__))  # 获取当前文件所在目录路径
# 拼接静态文件夹路径,这里假设静态文件夹名为 static，拼接好路径后为 /path/to/your/project/static
app.mount("/static", StaticFiles(directory=os.path.join(current_dir, 'static')), name="static")


@app.get("/")
async def test():
    return FileResponse(os.path.join(current_dir, 'static', 'index.html'))
# 将所有其他路由指向Vue应用
@app.get("/{page_name}")
async def read_page(page_name: str):
    return FileResponse(os.path.join(current_dir, 'static', 'index.html'))




if __name__ == '__main__':
    try:
        start_browser()  # 先打开浏览器
        uvicorn.run(app, host="localhost", port=17520)  # 然后启动FastAPI应用
    except Exception as e:
        print(f"启动失败：{e}")
        # 等待用户关闭窗口
        input("按任意键退出...")
        exit(1)

